import { useRequest } from 'ahooks';
import { Switch, message } from 'antd';

import { AppApiStatus, AppStatus } from '@/enum/app';
import { sysApplicationUpdate } from '@/services/base/quanxianmokuaiyingyongbiaojiekou';

import type { BizObject } from '.';

export type ApiSwitchProps = {
  data: BizObject;
  onChange: () => void;
};

const ApiSwitch: React.FC<ApiSwitchProps> = ({ data, onChange }) => {
  const switchStatus = useRequest(
    async (checked: boolean) => {
      const res = await sysApplicationUpdate(
        {
          ...data,
          status: checked ? AppStatus.启用 : AppStatus.禁用,
          apiStatus: checked ? data.apiStatus : AppApiStatus.禁用
        },
        {
          tupleResponse: false
        }
      );

      message.success(checked ? '开启 应用 成功' : '关闭 应用 成功');

      return res.data;
    },
    {
      onSuccess: () => {
        onChange();
      },
      manual: true
    }
  );

  return (
    <Switch
      checked={data.status === AppStatus.启用}
      onChange={(checked) => {
        switchStatus.run(checked);
      }}
      loading={switchStatus.loading}
      checkedChildren="开启"
      unCheckedChildren="关闭"
    />
  );
};

export default ApiSwitch;
